package com.bbb.controller;

import com.bbb.common.Code;
import com.bbb.common.Result;
import com.bbb.pojo.User;
import com.bbb.pojo.UserWorks;
import com.bbb.pojo.UserLike;
import com.bbb.pojo.WorksLike;
import com.bbb.service.RecommendationService;
import com.bbb.service.UserLikeService;
import com.bbb.service.UserService;
import com.bbb.service.UserWorksService;
import com.bbb.service.WorksLikeService;
import com.bbb.common.util.AuthUtil;
import lombok.var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/recommend")
public class RecommendationController {

    private static final Logger logger = LoggerFactory.getLogger(RecommendationController.class);

    @Autowired
    private RecommendationService recommendationService;

    @Autowired
    private UserWorksService userWorksService;

    @Autowired
    private WorksLikeService worksLikeService;

    @Autowired
    private UserLikeService userLikeService;

    @Autowired
    private UserService userService;

    @GetMapping("/works")
    public Result getRecommendedWorks() {
        try {
            Integer userId = AuthUtil.getUserId();
            if (userId == null) {
                logger.error("获取用户 ID 失败，无法生成推荐作品");
                return new Result(Code.GET_ERR, "获取用户 ID 失败，请重新登录", null);
            }
            List<UserWorks> recommendedWorks = recommendationService.generateRecommendations(userId);
            if (recommendedWorks.isEmpty()) {
                // 如果推荐作品为空，获取所有用户的作品并随机排序
                List<UserWorks> allUserWorks = userWorksService.list();
                Collections.shuffle(allUserWorks);
                recommendedWorks = allUserWorks;
                logger.info("用户 ID 为 {} 的推荐作品为空，展示所有用户的随机作品，数量: {}", userId, recommendedWorks.size());
            } else {
                logger.info("成功获取用户 ID 为 {} 的推荐作品，数量: {}", userId, recommendedWorks.size());
            }
            // 补充每个作品的额外信息
            for (UserWorks userWorks : recommendedWorks) {
                User user = userService.getById(userWorks.getUserId());
                userWorks.setAuthorName(Optional.ofNullable(user).map(User::getName).orElse(""));
                var userWorksWrapper = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<WorksLike>();
                userWorksWrapper.eq(WorksLike::getUserId, userId);
                userWorksWrapper.eq(WorksLike::getWorksId, userWorks.getId());
                userWorks.setLikeWork(worksLikeService.count(userWorksWrapper) > 0 ? 1 : 0);
                if (Objects.equals(userWorks.getUserId(), userId)) {
                    userWorks.setLikeAuthor(2);
                } else {
                    var userLikeWrapper = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserLike>();
                    userLikeWrapper.eq(UserLike::getUserId, userId);
                    userLikeWrapper.eq(UserLike::getAuthorId, userWorks.getUserId());
                    userWorks.setLikeAuthor(userLikeService.count(userLikeWrapper) > 0 ? 1 : 0);
                }
            }
            return new Result(Code.GET_OK, "获取推荐作品成功", recommendedWorks);
        } catch (Exception e) {
            logger.error("获取推荐作品时发生异常", e);
            return new Result(Code.GET_ERR, "获取推荐作品失败，请稍后重试", null);
        }
    }
}